const error = require('./error')

export const utils = {
  
  /**
   * 授权
   * @param _this
   * @returns {*}
   */
  getOauth(mchCode, _this) {
    
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })
    
    const data = {
      callbackUrl: window.location.href,
      mchCode: _this.cacheMchCode,
      oauthInfo: 1
    }
    
    ajax.post(_this.$apiRoute.oauth, _this.$qs.stringify(data))
      .then(function (response) {
        const data = response.data
        
        if (data.code !== 200) {
          console.log("授权失败===" + data.msg)
        }
        const redirectUrl = data.values.url
        // console.log(redirectUrl)
        window.location.href = redirectUrl
      })
  },
  
  /**
   * 授权
   * @param _this
   * @returns {*}
   */
   getPayOauth(_this) {
  
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })
  
    let data = {
      openid: _this.openid,
      callbackUrl: window.location.href,
      mchCode: _this.cacheMchCode,
    }
  
    return new Promise(function(resolve, reject) {
    
      ajax.post(_this.$apiRoute.payOauth, _this.$qs.stringify(data))
        .then(function (response) {
        
          let res = response.data

          if(res.values.openid != "") {
            resolve(res.values.openid);
          } else {
            window.location.href = res.values.url
          }
          
        })
    
    }).then(function(openid) {
      return openid;
    })
    
  },

  /**
   * 获取短信验证码
   * @param ajax
   * @param data
   * @param _this
   */
  getCode(ajax, data, _this) {
    ajax.post(_this.$apiRoute.bindMbSendMobileCode, _this.$qs.stringify(data))
      .then(function (result) {
        console.log(result)
        _this.showLoading = false
        if (result.data.code === 200) {
          _this.getCodeBtnText = 59
          const end = 0

          //倒计时
          // setInterval(function () {
          //   if (_this.getCodeBtnText > end) {
          //     _this.showGetCodeBtn = false
          //     _this.getCodeBtnText--
          //   } else {
          //     _this.showGetCodeBtn = true
          //   }
          // }, 1000)

          _this.showToast = true
          _this.toastType = 'success'
          _this.toastText = '短信发送成功'
        } else {
          _this.showAlert = true
          _this.alertText = result.data.msg

          setTimeout(function () {
            _this.$router.push(error[result.data.code])
          }, 1000)

        }
      })
  },

  /**
   * 异步获取mch类型
   * @param mchCode
   * @param _this
   * @returns {Promise.<TResult>}
   */
  getMchType(mchCode, _this) {

    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      mchCode: mchCode,
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.getMchType, _this.$qs.stringify(data))
        .then(function (response) {

          let res = response.data
          const values = {
            valid: true
          };

          if(res.code !== 200) {
            values["valid"] = false
            values["msg"] = res.msg
          } else {
            values["info"] = res.values
          }

          resolve(values);
        })

    }).then(function(type) {
      return type
    })

  },

  /**
   * 验证会员信息
   * @param openid
   * @param cacheMchCode
   * @param _this
   * @returns {Promise.<TResult>}
   */
  checkMbInfo(_this) {

    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      openid: _this.openid,
      mchCode: _this.cacheMchCode
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.checkMbInfo, _this.$qs.stringify(data))
        .then(function (response) {

          let res = response.data

          const values = {
            valid: true
          };

          if(res.code !== 200) {
            values["valid"] = false
            values["msg"] = res.msg
          } else {
            values["info"] = res.values
          }

          resolve(values)

        })

    }).then(function(data) {
      return data
    })

  },

  /**
   * 会员中心获取数据
   * @param openid
   * @param cacheMchCode
   * @param _this
   * @returns {Promise.<TResult>}
   */
  center(_this) {

    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      openid: _this.openid,
      mchCode: _this.cacheMchCode,
      cardNo: _this.cardNo
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.center, _this.$qs.stringify(data))
        .then(function (response) {

          let data = response.data

          if(data['code'] !== 200) {
            reject(data)
          } else {
            resolve(data['values'])
          }

        })

    }).then(function(data) {
      return data
    }, function (result) {
      _this.$router.push(error[result["code"]])
      return false
    })

  },

  /**
   * 会员卡详情
   * @param openid
   * @param cacheMchCode
   * @param _this
   * @returns {Promise.<TResult>}
   */
  memberCardInfo (openid, cacheMchCode, cardNo, _this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      openid: openid,
      mchCode: cacheMchCode,
      cardNo: cardNo
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.cardInfo, _this.$qs.stringify(data))
        .then(function (response) {

          let res = response.data

          let result = {};

          if(res.code !== 200) {
            result["valid"] = false
            result["msg"] = res.msg
          } else {
            result = res.values
            result['info']["valid"] = true
          }

          resolve(result)

        })

    }).then(function(data) {
      return data
    })

  },



  /**
   * 我的资料
   * @param openid
   * @param cacheMchCode
   * @param _this
   * @returns {Promise.<TResult>}
   */
  mbInfo (openid, cacheMchCode, _this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      openid: openid,
      mchCode: cacheMchCode,
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.mbInfo, _this.$qs.stringify(data))
        .then(function (response) {

          resolve(response.data)

        })

    }).then(function(data) {
      return data
    })

  },

  /**
   * 交易流水
   * @param openid
   * @param cacheMchCode
   * @param _this
   * @returns {Promise.<TResult>}
   */
  dealRecord (_this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      openid: _this.openid,
      mchCode: _this.cacheMchCode,
      pageNum: _this.pageNum
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.tradeList, _this.$qs.stringify(data))
        .then(function (response) {

          resolve(response.data)

        })

    }).then(function(data) {
      return data
    })

  },

  /**
   * 优惠券
   * @param openid
   * @param cacheMchCode
   * @param _this
   * @returns {Promise.<TResult>}
   */
  couponList (openid, cacheMchCode, _this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      openid: openid,
      mchCode: cacheMchCode,
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.couponList, _this.$qs.stringify(data))
        .then(function (response) {

          resolve(response.data)

        })

    }).then(function(data) {
      return data
    })

  },


  /**
   * 二维码字符串
   * @param openid
   * @param cacheMchCode
   * @param _this
   * @returns {Promise.<TResult>}
   */
  myQrcode (_this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      openid: _this.openid,
      mchCode: _this.cacheMchCode,
      cardNo: _this.cardNo
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.myQrcode, _this.$qs.stringify(data))
        .then(function (response) {

          resolve(response.data)

        })

    }).then(function(data) {
      return data
    })

  },

  /**
   * 唤起支付
   * @param _this
   * @returns {Promise.<TResult>}
   */
  getPay (_this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = JSON.stringify({
      req_type: 'online_order',
      mch_code: _this.cacheMchCode,
      pos_code: _this.posCode, //终端号
      bank_amount: (_this.addLimit * 100) + "",//交易金额
      bank_type: '2',
      trade_remark: '会员卡充值',//交易标签
      pay_user: _this.payOpenid,//false
      chnl_undisc_amount: '',//false
      mb_order_no: _this.mbOrderNo
    })

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.getPay, data)
        .then(function (response) {

          if(response.resp_code === 200) {
            resolve(response.data)
          } else {
            reject(response)
          }

        })

    }).then(function(data) {
      return data
    }, function (error) {
      return error
    })

  },


  /**
   * 购买会员卡发起支付
   * @param _this
   * @returns {Promise.<TResult>}
   */
  getPayBuyCard (_this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = JSON.stringify({
      req_type: 'online_order',
      mch_code: _this.cacheMchCode,
      pos_code: _this.posCode, //终端号
      bank_amount: _this.addLimit + "",//交易金额
      bank_type: '2',
      trade_remark: '会员卡充值',//交易标签
      pay_user: _this.payOpenid,//false
      chnl_undisc_amount: '',//false
      mb_order_no: _this.orderNo
    })

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.getPay, data)
        .then(function (response) {

          if(response.resp_code === 200) {
            resolve(response.data)
          } else {
            reject(response)
          }

        })

    }).then(function(data) {
      return data
    }, function (error) {
      return error
    })

  },


  /**
   * 缓期支付
   * @param _this
   * @returns {Promise.<TResult>}
   */
  getBalanceInfo (_this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      openid: _this.openid,
      mchCode: _this.cacheMchCode,
      cardNo: _this.cardNo
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.getBalanceInfo, _this.$qs.stringify(data))
        .then(function (response) {

          if(response.resp_code === 200) {
            resolve(response.data)
          } else {
            reject(response)
          }

        })

    }).then(function(data) {
      return data
    }, function (error) {
      return error
    })

  },

  /**
   * 生成优惠券订单（选择金额）
   * @param _this
   * @returns {Promise.<TResult>}
   */
  createRechargeDiscountOrder (_this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      openid: _this.openid,
      mchCode: _this.cacheMchCode,
      cardNo: _this.cardNo,
      discNo: _this.discNo
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.createRechargeDiscountOrder, _this.$qs.stringify(data))
        .then(function (response) {

          if(response.resp_code === 200) {
            resolve(response.data)
          } else {
            reject(response)
          }

        })

    }).then(function(data) {
      return data
    }, function (error) {
      return error
    })

  },


  /**
   * 充值（输入金额）
   * @param _this
   * @returns {Promise.<TResult>}
   */
  createRechargeOrder (_this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    let data = {
      openid: _this.openid,
      mchCode: _this.cacheMchCode,
      cardNo: _this.cardNo,
      amt: _this.iptNum * 100
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.createRechargeOrder, _this.$qs.stringify(data))
        .then(function (response) {

          if(response.resp_code === 200) {
            resolve(response.data)
          } else {
            reject(response)
          }

        })

    }).then(function(data) {
      return data
    }, function (error) {
      return error
    })

  },


  /**
   * 领卡成功后新增数据
   * @param _this
   * @returns {Promise.<TResult>}
   */
  addWechatMemberCard (_this) {
    const ajax = _this.$http.create({
      headers: {'content-type': 'application/x-www-form-urlencoded'}
    })

    const callBackData = {
      openid: _this.openid,
      mchCode: _this.cacheMchCode,
      cardNo: _this.cardNo
    }

    return new Promise(function(resolve, reject) {

      //判断是否需要授权，1不需要，3需要
      ajax.post(_this.$apiRoute.addWechatMemberCard, _this.$qs.stringify(callBackData))
        .then(function (response) {

          console.log(response)
          if (response.data.code === 200) {
            resolve()
          } else {
            reject(response['data']['msg'])
          }

        })

    }).then(function() {
      return true
    }, function (error) {
      _this.showLoading = false
      _this.showAlert = true
      _this.alertText = error

      return false
    })

  },


}
